<template>
  <view class="container">
    <view class="form-container">
      <view class="query-counter" v-if="userInfo">
        <text class="counter-icon">🎯</text>
        <text class="counter-text"
          >剩余查询次数：{{ userInfo.remaining_queries }}</text
        >
        <text class="share-tip">分享给好友，每次被点击可获得5次查询机会~</text>
      </view>
      <view class="form-item">
        <text class="label">宝宝姓氏</text>
        <view class="input-wrapper">
          <input
            v-model="formData.surname"
            class="input"
            placeholder="请输入姓氏（必填）"
            maxlength="2"
            @input="validateSurname"
          />
          <text class="input-counter">{{ formData.surname.length }}/2</text>
        </view>
        <text v-if="errors.surname" class="error-text">{{
          errors.surname
        }}</text>
      </view>

      <view class="form-item">
        <text class="label">宝宝性别</text>
        <view class="gender-buttons">
          <view
            class="gender-btn"
            :class="{ active: formData.gender === '男' }"
            @tap="handleGenderSelect('男')"
          >
            <text class="gender-icon">👦</text>
            <text>男宝</text>
          </view>
          <view
            class="gender-btn"
            :class="{ active: formData.gender === '女' }"
            @tap="handleGenderSelect('女')"
          >
            <text class="gender-icon">👧</text>
            <text>女宝</text>
          </view>
        </view>
        <text v-if="errors.gender" class="error-text">{{ errors.gender }}</text>
      </view>

      <view class="form-item">
        <text class="label">字辈传承</text>
        <view class="input-wrapper">
          <input
            v-model="formData.generation"
            class="input"
            placeholder="请输入字辈（选填）"
            maxlength="2"
            @input="validateGeneration"
          />
          <text class="input-counter">{{ formData.generation.length }}/1</text>
        </view>
        <text v-if="errors.generation" class="error-text">{{
          errors.generation
        }}</text>
      </view>

      <view class="form-item">
        <text class="label">五行辅助运程</text>
        <view class="input-wrapper">
          <input
            v-model="formData.fiveElements"
            class="input"
            placeholder="（选填）,例：2025年1月1日 十点二十分"
            maxlength="30"
          />
          <text class="input-counter"
            >{{ formData.fiveElements.length }}/30</text
          >
        </view>
      </view>

      <view class="form-item">
        <text class="label">寄托美好寓意</text>
        <view class="input-wrapper">
          <input
            v-model="formData.meaning"
            class="input"
            placeholder="（选填），例：健康、平安"
            maxlength="20"
          />
          <text class="input-counter">{{ formData.meaning.length }}/20</text>
        </view>
      </view>

      <view class="form-item">
        <text class="label">出自典雅诗词</text>
        <view class="input-wrapper">
          <input
            v-model="formData.poetry"
            class="input"
            placeholder="（选填），例：诗经、唐诗"
            maxlength="20"
          />
          <text class="input-counter">{{ formData.poetry.length }}/20</text>
        </view>
      </view>
    </view>
    <!-- 添加底部占位 -->
    <view class="bottom-safe-area"></view>

    <view class="submit-btn-wrapper safe-area-inset-bottom">
      <button class="submit-btn" @tap="handleSubmit" :disabled="isGenerating">
        开始起名
      </button>
    </view>
  </view>
</template>



<script>
import { generateName } from "../../api/naming";
import { shareReward } from "../../api/auth";
import { getUserInfo, getStoredUserInfo } from "../../api/user";
import { waitForLogin } from "../../api/loginState";

export default {
  data() {
    return {
      isGenerating: false,
      isLoadingUser: true,
      userInfo: null,
      formData: {
        surname: "",
        gender: "",
        generation: "",
        fiveElements: "",
        meaning: "",
        poetry: "",
      },
      errors: {
        surname: "",
        gender: "",
        generation: "",
      },

      sharerId: ""
    };
  },
  async mounted() {
    try {
      // 等待登录完成
      await waitForLogin();
      
      // 获取URL中的sharer_id参数
      const query = uni.getLaunchOptionsSync().query;
      this.sharerId = query.sharer_id || '';

      await this.getUserInfo();
      // 如果有sharer_id，调用分享奖励接口
      if (this.sharerId) {
        await shareReward({ sharer_id: this.sharerId });
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
    }
  },
  async onShow() {
    await waitForLogin();
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      // 无论是否有本地缓存，都重新获取最新的用户信息
      const res = await getUserInfo();
      if (res.data) {
        this.userInfo = res.data;
      }
    },
    validateSurname() {
      const chineseReg = /^[\u4e00-\u9fa5]{1,2}$/;
      if (!this.formData.surname) {
        this.errors.surname = "请输入姓氏";
      } else if (!chineseReg.test(this.formData.surname)) {
        this.errors.surname = "请输入正确的中文姓氏";
      } else {
        this.errors.surname = "";
      }
    },

    validateGeneration() {
      const chineseReg = /^[\u4e00-\u9fa5]{1}$/;
      if (
        this.formData.generation &&
        !chineseReg.test(this.formData.generation)
      ) {
        this.errors.generation = "请输入单个汉字";
      } else {
        this.errors.generation = "";
      }
    },

    handleGenderSelect(gender) {
      this.formData.gender = gender;
      this.errors.gender = "";
    },

    async handleSubmit() {
      if (this.isGenerating) return;

      // 验证表单
      this.validateSurname();
      this.validateGeneration();

      if (!this.formData.gender) {
        this.errors.gender = "请选择性别";
      }

      if (this.errors.surname || this.errors.gender || this.errors.generation) {
        return;
      }

      try {
        this.isGenerating = true;
        uni.showLoading({
          title: "正在生成...",
          mask: true,
        });

        // 保存表单数据
        uni.setStorageSync("naming_form_data", {
          surname: this.formData.surname,
          gender: this.formData.gender,
          generation_word: this.formData.generation || undefined,
          five_elements: this.formData.fiveElements || undefined,
          meaning_tags: this.formData.meaning || undefined,
          poetry_source: this.formData.poetry || undefined,
        });

        const result = await generateName({
          surname: this.formData.surname,
          gender: this.formData.gender,
          generation_word: this.formData.generation || undefined,
          five_elements: this.formData.fiveElements || undefined,
          meaning_tags: this.formData.meaning || undefined,
          poetry_source: this.formData.poetry || undefined,
        });
        uni.setStorageSync("naming_result", result);

        // 跳转到结果页面
        uni.navigateTo({
          url: "/pages/result/result",
        });
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: error.message || "生成失败，请重试",
          icon: "none",
        });
      } finally {
        this.isGenerating = false;
      }
    },
  },

  onShareAppMessage() {
    const path = this.userInfo
      ? `/pages/index/index?sharer_id=${this.userInfo.user_id}`
      : "/pages/index/index";
    return {
      title: "快来给宝宝起个好名字吧",
      path: path,
      success: () => {},
    };
  },

  onShareTimeline() {
    return {
      title: "快来给起个好名字吧",
    };
  },
};
</script>

<style lang="less" scoped>
.container {
  padding: 30rpx;
  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: calc(180rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(180rpx + env(safe-area-inset-bottom));
}

.bottom-safe-area {
  height: 120rpx;
}

.submit-btn-wrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 30rpx;
  background: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);

  &.safe-area-inset-bottom {
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  }
}

.submit-btn {
  background: #1677ff;
  color: #fff;
  border-radius: 8rpx;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;

  &:active {
    opacity: 0.9;
  }

  &:disabled {
    background: #ccc;
    opacity: 0.7;
    cursor: not-allowed;
  }
}
.form-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.query-counter {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  margin-bottom: 30rpx;
  padding: 16rpx;
  background: #f0f7ff;
  border-radius: 8rpx;

  .counter-icon {
    font-size: 32rpx;
  }

  .counter-text {
    font-size: 28rpx;
    color: #1677ff;
  }

  .share-tip {
    font-size: 24rpx;
    color: #666;
    margin-top: 4rpx;
  }
}

.form-item {
  margin-bottom: 32rpx;

  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 12rpx;
    display: block;
  }
}

.input-wrapper {
  position: relative;

  .input {
    height: 88rpx;
    background: #f5f5f5;
    border-radius: 8rpx;
    padding: 0 24rpx;
    padding-right: 80rpx;
    font-size: 28rpx;
    width: 100%;
    box-sizing: border-box;
  }

  .input-counter {
    position: absolute;
    right: 24rpx;
    bottom: 24rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.error-text {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 8rpx;
}

.gender-buttons {
  display: flex;
  gap: 30rpx;

  .gender-btn {
    flex: 1;
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    border-radius: 8rpx;
    gap: 12rpx;

    &.active {
      background: #1677ff;
      color: #fff;
    }
  }

  .gender-icon {
    font-size: 32rpx;
  }
}
</style>